const router = require('koa-router')();
const { name, response, } = require('../public/javascripts/utils');
const item = require("../service/users")

const jwt = require('jsonwebtoken');
const config = require('../config');
const generateToken = require('../public/javascripts/authController').generateToken;
// 设置路由前缀
router.prefix(`/${name(__filename)}`);
// 定义路由
router.get('/', async (ctx, next) => {
  try {
    const res = await item.findAll(ctx.query);
    response(ctx, res.res, res.total)
  } catch (err) {
    response(ctx,null,null,500, '服务器错误')
  }
});


router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body;
  if (!username || !password) {
    return response(ctx, null, null, 400, '缺少必要参数');
  }
  try {
    let user = await item.find({ username });
    console.log("查询结果")
    if (!user) {
      ctx.status = 401;
      ctx.body = { message: '未注册账户' };
      return;
    }
    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      ctx.status = 401;
      ctx.body = { message: '密码错误' };
      return;
    }
    const token = generateToken(user._id);
    // const token = jwt.sign({ userId: user._id }, config.JWT_SECRET, { expiresIn: '1h' });
    // ctx.body = { token, user: { username: user.username, email: user.email, roles: user.roles } };
    user.password = null;
    response(ctx, { token, user });
  } catch (error) {}
})


router.post('/register', async (ctx, next) =>{ //  添加或者更新
  // 验证请求体
  const { username, password } = ctx.request.body;
  if (!username  || !password) {
    return response(ctx, null, null, 400, '缺少必要参数');
  }
  try {
    const para = ctx.request.body
    let res = null
    if (para._id) {
      res = await item.update(para._id, para);
    } else {
      res = await item.create(para);
    }
  
    response(ctx, res);
  } catch (error) {
    console.log(error)
    if (error) {
      ctx.response.body = {
        code: 400,
        msg: '账号已存在',
        data: null,
      };
    } else {
      response(ctx, null, null, 500, '服务器错误');
    }
  }
})



module.exports = router;